package com.sdry.untils;

import com.sdry.system.entity.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @program: info_sdry
 * @description: 获取session
 * @author: cb
 * @create: 2020-02-19 14:47
 **/
public class UserContext {

    public final static String userInSession="user";

    /**
     * 反向获取request与session
     * @return
     */
    private static HttpSession getSession(){
        HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getSession();
    }

    /**
     * 获取用户名
     * @return
     */
    public static String getSessionUserNameByServiceImpl(){
        SysUser user = (SysUser) getSession().getAttribute(userInSession);
        if (user != null) {
            if (StringUtils.isNotEmpty(user.getRealName())){
                return user.getRealName();
            }else {
                return "用户";
            }

        }
        return "用户";
    }

    /**
     * 获取用户名ID
     * @return
     */
    public static Long getSessionUserIdByServiceImpl(){
        SysUser user = (SysUser) getSession().getAttribute(userInSession);
        if (user != null) {
            if (StringUtils.isNotEmpty(user.getRealName())){
                return user.getUserId();
            }else {
                return 0L;
            }

        }
        return 0L;
    }

}
